//Component Object
let currentTimeStorageKey = 'voiceIcon_'
Component({
  options: {
    pureDataPattern: /^_/ // 指定所有 _ 开头的数据字段为纯数据字段
  },
  pageLifetimes: {
    hide: function () {
      // console.log('pageLifetimes hide')
      let that = this as any
      that.pauseVoice()
    }
  },
  properties: {
    recordId: {
      type: String
    },
    audioUrl: {
      type: String,
      observer: function (newValue: string) {
        let that = this as any
        this.setData({
          progress:0
        })
        this.data._currentTime = 0
        const deviceInfo = wx.getDeviceInfo()
        let isIos = deviceInfo.system.toLowerCase().includes('ios')
        if (isIos) {
          this.setData({
            finalAudioUrl: newValue
          })
        } else {
          // 安卓的话，需要先把文件下载下来才能播放
          wx.downloadFile({
            url: newValue,
            success: (res) => {
              // console.log('download res:',res)
              // console.log('that.data._audioContext2:',that.data._audioContext)
              if (res.statusCode === 200) {
                that.setData({
                  finalAudioUrl: res.tempFilePath
                })
              }
            }
          })
        }
      }
    },
    voiceDuration: {
      type: Number,
      value: 0
    },
    playingAudioUrl: {
      type: String,
      value: '',
      observer: function (newValue: string) {
        let that = this as any
        if (
          newValue !== that.data.audioUrl &&
          that.data.playStatus === 'play'
        ) {
          that.pauseVoice()
        }
      }
    },
    pageIndex: {
      type: Number
    },
    curSwiperIndex: {
      type: Number,
      observer: function (newValue: number) {
        // console.log('curSwiperIndex:',newValue)
        let that = this as any
        if (newValue == that.data.pageIndex) {
          // 只有5个以内，才初始化播放器，避免初始化过多播放器
          // console.log('初始化播放器：',this.data.index)
          that.initAudioContext()
        } else {
          // 不删除播放器，避免切换回来时，需要重新初始化
          // that.destoryAudioContext()
          that.pauseVoice()
        }
      }
    }
  },
  data: {
    playStatus: 'pause',
    _audioContext: null,
    _canTap: true,
    progress: 0,
    duration: 0,
    _currentTime: 0,
    finalAudioUrl: '',
  },
  methods: {
    setProgress(currentTime: number) {
      let that = this as any
      let progress = Math.ceil((currentTime / that.data.voiceDuration) * 100)
      if (progress > 100) {
        progress = 100
      }
      that.setData({
        progress: progress
      })
    },
    initAudioContext() {
      console.log('initAudioContext')
      let that = this as any
      // 如果没有音频地址，则不初始化
      if (!that.data.audioUrl) {
        return
      }
      if(that.data._audioContext){
        console.log('已经初始化了，不需要再初始化')
        return
      }
      let _audioContext = wx.createInnerAudioContext({
        useWebAudioImplement: false
      }) as any
      _audioContext.onCanplay(() => {
        let duration = _audioContext.duration
      })

      _audioContext.onPlay(() => {
        // console.log('onCanplay that：',that)
        // console.log('audioContext2:',audioContext)
        that.setData({
          playStatus: 'play'
        })
      })
      _audioContext.onTimeUpdate(() => {
        // console.log('audioContext.currentTime:',_audioContext.currentTime)
        // console.log('voiceDuration:',that.data.voiceDuration)
        that.setProgress(_audioContext.currentTime)
      })

      _audioContext.onPause(() => {
        that.setData({
          playStatus: 'pause'
        })
        console.log('_audioContext.currentTime:', _audioContext.currentTime)
        // wx.setStorageSync(currentTimeStorageKey,_audioContext.currentTime)
        this.data._currentTime = _audioContext.currentTime
      })

      _audioContext.onStop(() => {
        that.setData({
          playStatus: 'pause'
        })
        console.log('_audioContext.currentTime:', _audioContext.currentTime)
        // wx.setStorageSync(currentTimeStorageKey,_audioContext.currentTime)
        this.data._currentTime = _audioContext.currentTime
      })
      _audioContext.onEnded(() => {
        // console.log('onEnded')
        that.setData({
          playStatus: 'pause'
        })
        // wx.setStorageSync(currentTimeStorageKey,0)
        this.data._currentTime = 0
        that.setProgress(0)
      })

      

      that.setData({
        _audioContext
      })
    },
    destoryAudioContext() {
      let that = this as any
      if (that.data._audioContext) {
        that.pauseVoice()
        that.data._audioContext.destroy()
        that.data._audioContext = null
      }
    },
    playVoice() {
      console.log('playVoice')
      if (this.data._canTap) {
        this.data._canTap = false
        setTimeout(() => {
          this.data._canTap = true
        }, 200)
        let that = this as any
        if (!that.data._audioContext) {
          console.log('初始化音频播放器失败')
          return
        }

        console.log('that.data._currentTime:', that.data._currentTime)
        if (that.data.playStatus === 'pause') {
          that.triggerEvent('parentPlayThisAudio', {
            audioUrl: that.data.audioUrl
          })
          that.data._audioContext.src= that.data.finalAudioUrl
          if(that.data._currentTime){
            that.data._audioContext.seek(that.data._currentTime)
          }

          that.data._audioContext.play()
        } else {
          that.data._audioContext.pause()
          that.triggerEvent('parentPlayThisAudio', { audioUrl: '' })
        }
      }
    },
    pauseVoice() {
      let that = this as any
      // console.log('pauseVoice')
      if (that.data._audioContext) {
        that.data._audioContext.pause()
        that.setData({
          playStatus: 'pause'
        })
      }
    }
  },

  attached: function () {
    if(this.data.curSwiperIndex === this.data.pageIndex){
      this.initAudioContext()
    }
  },
  detached: function () {
    // 在组件实例被从页面节点树移除时执行
    // console.log('voiceionc detached')
    if (this.data._audioContext) {
      this.pauseVoice()
      this.data._audioContext.destroy()
      this.data._audioContext = null
    }
    wx.removeStorageSync(currentTimeStorageKey)
  }
})
